package cn.jlearn.proxy.web.controller.open;

import cn.jlearn.proxy.web.convert.TunnelConvert;
import cn.jlearn.proxy.web.model.DownAgent;
import cn.jlearn.proxy.web.model.Tunnel;
import cn.jlearn.proxy.web.pojo.R;
import cn.jlearn.proxy.web.service.HomeService;
import cn.jlearn.proxy.web.service.TunnelService;
import cn.jlearn.proxy.web.vo.TunnelInfoVO;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author qianyingchao
 * @version 1.0
 * @date 2021/7/16 5:21 下午
 */
@RestController
@RequestMapping(value = "/api/open/proxy/client")
public class ProxyClientController {

    @Resource
    private HomeService homeService;

    @Resource
    private TunnelService tunnelService;

    @Resource
    private TunnelConvert tunnelConvert;

    @GetMapping(value = "/version/check")
    public R<?> versionCheck(@RequestParam String version) {
        DownAgent agent = homeService.getLatestAgent();
        if (agent.getVersion().equals(version)) {
            return R.success();
        } else {
            return R.fail("416", "当前app不是最新版本，请下载最新版");
        }
    }

    @GetMapping(value = "/tunnel/{token}")
    public R<TunnelInfoVO> tunnelInfo(@PathVariable("token") String token) {
        Tunnel tunnel = tunnelService.getTunnelByToken(token);
        if (tunnel != null) {
            return R.success(tunnelConvert.toTunnelInfoVO(tunnel));
        }
        return R.success();
    }

    @PostMapping(value = "/tunnel/{token}")
    public R<?> tunnelOnline(@PathVariable("token") String token, @RequestBody JSONObject params) {
        return tunnelService.online(token, params.getString("online"));
    }

}
